package com.example.sunray.bluetooth.SSP;

import com.example.sunray.bluetooth.Config.DataConfig;

/**
 * Created by wangjianqiang on 2018/7/10 14:56.
 * Package name com.example.sunray.bluetooth.SSP
 */
public class Decode {

    public static boolean isIntegrity(byte[] data) {
        try {
            byte[] readData = getRealData(data);
            int calCrc1 = CRC16.calcCrc16(readData);
            int srcCrcl = getCrcl(data[1022], data[1023]);
            if (calCrc1 == srcCrcl) {
                return true;
            }
        } catch (Exception e) {

        }
        return false;
    }

    public static byte[] getRealData(byte[] data) {
        byte[] realData = new byte[DataConfig.DATA_LENGTH - 2];
        System.arraycopy(data, 0, realData, 0, DataConfig.DATA_LENGTH - 2);
        return realData;
    }

    public static int getCrcl(byte high, byte low) {
        return ((high & 0x00ff) << 8) | (low & 0x00ff) & 0xffff;
    }

    public static int getAction(byte[] data) {
        return data[1];
    }
    public static byte[] getContent(byte[] data){
        int length = (int)getContentLength(data);
        byte[] content = new byte[length];
        System.arraycopy(data,6,content,0,length);
        return content;
    }
    public static long getContentLength(byte[] data) {
        int type = data[1];
        long length = 0;
        switch (type) {
            case DataConfig.DATA_START:
                byte leng0 = data[4];
                byte leng1 = data[5];
                byte leng2 = data[6];
                byte leng3 = data[7];
                length = ((leng0 & 0xff) << 32) | ((leng1 & 0xff) << 16) | ((leng2 & 0xff) << 8) | (leng3 & 0x00ff) & 0xffff;
                break;
            case DataConfig.DATA_RECEIVING:
                byte dataLength0 = data[4];
                byte dataLength1 = data[5];
                length = ((dataLength0 & 0xff) << 8) | (dataLength1 & 0x00ff) & 0xffff;
                break;
        }
        return length;
    }
}
